package com.example.myapplication;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;
import okhttp3.*;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Objects;

import org.json.JSONException;

public class MainActivity extends AppCompatActivity {
    private TextInputEditText usernameInput;
    private TextInputEditText passwordInput;
    private final OkHttpClient client = new OkHttpClient();
//    private static final String LOGIN_URL = "http://192.168.91.25:3002/api/auth/login"; // 替换为实际的登录API地址
private static final String LOGIN_URL = "http://192.168.1.104:3002/api/auth/login"; // 替换为实际的登录API地址

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化视图
        usernameInput = findViewById(R.id.username);
        passwordInput = findViewById(R.id.password);
        MaterialButton loginButton = findViewById(R.id.login_button);

        // 设置默认值
        usernameInput.setText("admin");
        passwordInput.setText("admin123");

        // 设置登录按钮点击事件
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = Objects.requireNonNull(usernameInput.getText()).toString();
                String password = Objects.requireNonNull(passwordInput.getText()).toString();
                
                // 验证输入
                if (username.isEmpty() || password.isEmpty()) {
                    Toast.makeText(MainActivity.this, "用户名和密码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                // 执行登录请求
                performLogin(username, password);
            }
        });
    }

  private void performLogin(String username, String password) {
    try {
        // 创建JSON数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", username);
        jsonObject.put("password", password);

        // 创建请求体
        RequestBody requestBody = RequestBody.create(
            jsonObject.toString(),
            MediaType.parse("application/json; charset=utf-8")
        );

        // 构建请求
        Request request = new Request.Builder()
            .url(LOGIN_URL)
            .post(requestBody)
            .build();

        // 异步执行请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(MainActivity.this,
                        "登录失败: " + e.getMessage(),
                        Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String responseBody = "";
                if (response.body() != null) {
                    responseBody = response.body().string();
                }
                String finalResponseBody = responseBody;
                runOnUiThread(() -> {
                    try (response) {
                        if (response.isSuccessful()) {
                            // 解析返回的用户信息
                            JSONObject jsonResponse = new JSONObject(finalResponseBody);
                            if (jsonResponse.getInt("code") == 0) {
                                Log.d("TAG", String.valueOf(jsonResponse));
                                JSONObject data = jsonResponse.getJSONObject("data");
                                String token = data.getString("accessToken");

                                // 存储 token 和 refreshToken
                                getSharedPreferences("MyAppPrefs", MODE_PRIVATE)
                                    .edit()
                                    .putString("accessToken", token)
                                    .apply();
Toast.makeText(MainActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
                                // 跳转到个人信息页面
                                Intent intent = new Intent(MainActivity.this, MainActivity2.class);
                                intent.putExtra("userInfo", data.getJSONObject("user").toString()); // 确保传递的是 JSON 字符串
                                startActivity(intent);
                                finish(); // 关闭登录页面

                            } else {
                                Toast.makeText(MainActivity.this,
                                        "登录失败: " + jsonResponse.getString("message"),
                                        Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(MainActivity.this,
                                    "登录失败: " + finalResponseBody,
                                    Toast.LENGTH_SHORT).show();
                        }
                    } catch (Exception e) {
                        Toast.makeText(MainActivity.this,
                                "数据解析错误: " + e.getMessage(),
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

    } catch (Exception e) {
        Toast.makeText(MainActivity.this,
                "发生错误: " + e.getMessage(),
                Toast.LENGTH_SHORT).show();
    }
}
    @NonNull
    private static UserInfo getUserInfo(String finalResponseBody) throws JSONException {
        JSONObject jsonResponse = new JSONObject(finalResponseBody);
        JSONObject userJson = jsonResponse.getJSONObject("data").getJSONObject("user");

        UserInfo userInfo = new UserInfo();
        userInfo.setId(userJson.getInt("id"));
        userInfo.setUsername(userJson.getString("realName"));
        userInfo.setAccount(userJson.getString("username"));
        userInfo.setEmail(userJson.optString("email"));
        return userInfo;
    }
}
